<?php

namespace App\Support;

use App\Controller\Ws\ServerController;
use Hyperf\Di\Annotation\Inject;
use RedisException;
use function _PHPStan_b8e553790\RingCentral\Psr7\str;

class WebSocket
{

    public $prefixFdToUser = 'ws:fd-user:';
    public $prefixUseToFd = 'ws:user-fd:';


    /**
     * @Inject()
     * @var ServerController
     */
    public $server;


    /**
     * ws连接绑定
     * @param $uid
     * @param $fd
     * @param $server
     * @return true
     * @throws RedisException
     */
    public function bind($uid, $fd, $server = SERVER_RUN_ID)
    {

        redis()->hSet($this->prefixFdToUser . $server, strval($fd), $uid);
        redis()->hSet($this->prefixUseToFd . $server, strval($uid), $fd);
        return true;
    }

    /**
     * ws连接解除绑定
     * @param $uid
     * @param $fd
     * @param $server
     * @return true
     * @throws RedisException
     */
    public function unBind($uid, $fd, $server = SERVER_RUN_ID)
    {

        redis()->hDel($this->prefixFdToUser . $server, strval($fd));
        redis()->hDel($this->prefixUseToFd . $server, strval($uid));
        return true;
    }



    public function forceOffline($uid, $fd, $server = SERVER_RUN_ID){



    }

    /**
     * 通过fd 找 uid
     * @param $fd
     * @param $server
     * @return false|\Redis|string
     * @throws RedisException
     */
    public function getUidByFd($fd,$server = SERVER_RUN_ID){

        return redis()->hGet($this->prefixFdToUser.$server,strval($fd));
    }

    /**
     * 通过 uid 找 fd
     * @param $uid
     * @param $server
     * @return false|\Redis|string
     * @throws RedisException
     */
    public function getFdByUid($uid,$server = SERVER_RUN_ID){

        return redis()->hGet($this->prefixUseToFd.$server,strval($uid));
    }


    /**
     * 删除ws相关的所有key
     * @return true
     * @throws RedisException
     */
    public function deleteAll()
    {
        redisScanDel('ws:');
        return true;
    }

}